{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <h2>能力素质管理</h2>
        
        {% if current_user.role == 'student' %}
            <div class="card mt-4">
                <div class="card-header">
                    <h4>提交能力素质评分</h4>
                </div>
                <div class="card-body">
                    <form method="POST" action="{{ url_for('submit_ability') }}" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        
                        <div class="mb-3">
                            <label class="form-label">学期</label>
                            <select class="form-select" name="semester" required>
                                <option value="">请选择学期</option>
                                <option value="2023-2024">2023-2024</option>
                                <option value="2024-2025">2024-2025</option>
                            </select>
                        </div>

                        <!-- 学术科技能力分 -->
                        <div class="mb-3">
                            <label class="form-label">学术科技能力分</label>
                            <div id="academic-items">
                                <div class="row mb-2">
                                    <div class="col-md-6">
                                        <select class="form-select" name="academic_items[]">
                                            <option value="">请选择项目</option>
                                            <option value="1">发表学术论文</option>
                                            <option value="2">参与科研项目</option>
                                            <option value="3">获得专利</option>
                                            <option value="4">参加学科竞赛</option>
                                            <option value="5">学术讲座</option>
                                            <option value="other">其他</option>
                                        </select>
                                        <input type="text" class="form-control mt-2 other-input" name="academic_other[]" style="display: none;" placeholder="请输入其他加分内容">
                                    </div>
                                    <div class="col-md-4">
                                        <input type="number" class="form-control" name="academic_scores[]" step="1" min="0" max="50" placeholder="分数" required>
                                    </div>
                                    <div class="col-md-2">
                                        <button type="button" class="btn btn-secondary btn-sm" onclick="addItem('academic')">+</button>
                                        <button type="button" class="btn btn-danger btn-sm" onclick="removeItem(this)">删除</button>
                                    </div>
                                </div>
                            </div>
                            <button type="button" class="btn btn-secondary btn-sm mt-2" onclick="addBonusItem()" id="add-bonus-btn">
                                <i class="bi bi-plus"></i> 添加其他项
                            </button>
                        </div>

                        <!-- 社会实践能力分 -->
                        <div class="mb-3">
                            <label class="form-label">社会实践能力分</label>
                            <div id="social-items">
                                <div class="row mb-2">
                                    <div class="col-md-6">
                                        <select class="form-select" name="social_items[]">
                                            <option value="">请选择项目</option>
                                            <option value="1">社会调研</option>
                                            <option value="2">志愿服务</option>
                                            <option value="3">实习实践</option>
                                            <option value="4">创新创业</option>
                                            <option value="5">社会公益</option>
                                            <option value="other">其他</option>
                                        </select>
                                        <input type="text" class="form-control mt-2 other-input" name="social_other[]" style="display: none;" placeholder="请输入其他项目内容">
                                    </div>
                                    <div class="col-md-4">
                                        <input type="number" class="form-control" name="social_scores[]" step="1" min="0" max="20" placeholder="分数" required>
                                    </div>
                                    <div class="col-md-2">
                                        <button type="button" class="btn btn-secondary btn-sm" onclick="addItem('social')">+</button>
                                        <button type="button" class="btn btn-danger btn-sm" onclick="removeItem(this)">删除</button>
                                    </div>
                                </div>
                            </div>
                            <button type="button" class="btn btn-secondary btn-sm mt-2" onclick="addBonusItem()" id="add-bonus-btn">
                                <i class="bi bi-plus"></i> 添加其他项
                            </button>
                        </div>

                        <!-- 综合技能分 -->
                        <div class="mb-3">
                            <label class="form-label">综合技能分</label>
                            <div id="skill-items">
                                <div class="row mb-2">
                                    <div class="col-md-6">
                                        <select class="form-select" name="skill_items[]">
                                            <option value="">请选择项目</option>
                                            <option value="1">外语能力</option>
                                            <option value="2">计算机技能</option>
                                            <option value="3">职业资格证书</option>
                                            <option value="4">艺术特长</option>
                                            <option value="5">体育特长</option>
                                            <option value="other">其他</option>
                                        </select>
                                        <input type="text" class="form-control mt-2 other-input" name="skill_other[]" style="display: none;" placeholder="请输入其他项目内容">
                                    </div>
                                    <div class="col-md-4">
                                        <input type="number" class="form-control" name="skill_scores[]" step="1" min="0" max="30" placeholder="分数" required>
                                    </div>
                                    <div class="col-md-2">
                                        <button type="button" class="btn btn-secondary btn-sm" onclick="addItem('skill')">+</button>
                                        <button type="button" class="btn btn-danger btn-sm" onclick="removeItem(this)">删除</button>
                                    </div>
                                </div>
                            </div>
                            <button type="button" class="btn btn-secondary btn-sm mt-2" onclick="addBonusItem()" id="add-bonus-btn">
                                <i class="bi bi-plus"></i> 添加其他项
                            </button>
                        </div>

                        <!-- 证明材料上传 -->
                        <div class="mb-3">
                            <label class="form-label">附件证明材料（选填）</label>
                            <input type="file" class="form-control" name="proof_file" accept=".pdf,.jpg,.jpeg,.png">
                            <div class="form-text">支持PDF、JPG、PNG格式，大小不超过5MB</div>
                        </div>

                        <button type="submit" class="btn btn-primary">提交评分</button>
                    </form>
                </div>
            </div>

            <!-- 显示历史记录 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>我的能力素质记录</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>学期</th>
                                <th>学术科技能力</th>
                                <th>社会实践能力</th>
                                <th>综合技能</th>
                                <th>总分</th>
                                <th>状态</th>
                                <th>附件</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for record in ability_records %}
                            <tr>
                                <td>{{ record.semester }}</td>
                                <td>
                                    {% for item in record.academic_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>
                                    {% for item in record.social_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>
                                    {% for item in record.skill_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>{{ record.total_score }}</td>
                                <td>
                                    {% if record.status == 'pending' %}
                                        <span class="badge bg-warning">待审核</span>
                                    {% elif record.status == 'approved' %}
                                        <span class="badge bg-success">已通过</span>
                                    {% else %}
                                        <span class="badge bg-danger">已驳回</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if record.proof_file %}
                                        <a href="{{ url_for('download_ability_proof', file_id=record.id) }}" class="btn btn-sm btn-secondary">
                                            查看附件
                                        </a>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        {% else %}
            <!-- 教师查看界面 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>待审核能力素质</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>学生</th>
                                <th>学期</th>
                                <th>学术科技能力</th>
                                <th>社会实践能力</th>
                                <th>综合技能</th>
                                <th>总分</th>
                                <th>提交时间</th>
                                <th>状态</th>
                                <th>附件</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for record in ability_records %}
                            {% if record.status == 'pending' %}
                            <tr>
                                <td>{{ record.student.username }} - {{ record.student.real_name }}</td>
                                <td>{{ record.semester }}</td>
                                <td>
                                    {% for item in record.academic_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>
                                    {% for item in record.social_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>
                                    {% for item in record.skill_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>{{ record.total_score }}</td>
                                <td>{{ record.submit_time.strftime('%Y-%m-%d %H:%M') }}</td>
                                <td>
                                    <span class="badge bg-warning">待审核</span>
                                </td>
                                <td>
                                    {% if record.proof_file %}
                                        <a href="{{ url_for('download_ability_proof', file_id=record.id) }}" class="btn btn-sm btn-secondary">
                                            查看附件
                                        </a>
                                    {% endif %}
                                </td>
                                <td>
                                    <button type="button" class="btn btn-sm btn-success" onclick="approveScore('ability', {{ record.id }})">通过</button>
                                    <button type="button" class="btn btn-sm btn-danger" onclick="rejectScore('ability', {{ record.id }})">驳回</button>
                                </td>
                            </tr>
                            {% endif %}
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 已审核成绩表格 -->
            <div class="card mt-4">
                <div class="card-header">
                    <h4>已审核能力素质</h4>
                </div>
                <div class="card-body">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>学生</th>
                                <th>学期</th>
                                <th>学术科技能力</th>
                                <th>社会实践能力</th>
                                <th>综合技能</th>
                                <th>总分</th>
                                <th>提交时间</th>
                                <th>审核时间</th>
                                <th>状态</th>
                                <th>附件</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for record in ability_records %}
                            {% if record.status != 'pending' %}
                            <tr>
                                <td>{{ record.student.username }} - {{ record.student.real_name }}</td>
                                <td>{{ record.semester }}</td>
                                <td>
                                    {% for item in record.academic_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>
                                    {% for item in record.social_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>
                                    {% for item in record.skill_items %}
                                        {% if item.item == 'other' %}
                                            {{ item.other_content }}：{{ item.score }}分<br>
                                        {% else %}
                                            {{ item.item }}：{{ item.score }}分<br>
                                        {% endif %}
                                    {% endfor %}
                                </td>
                                <td>{{ record.total_score }}</td>
                                <td>{{ record.submit_time.strftime('%Y-%m-%d %H:%M') }}</td>
                                <td>{{ record.update_time.strftime('%Y-%m-%d %H:%M') if record.update_time else '' }}</td>
                                <td>
                                    {% if record.status == 'approved' %}
                                        <span class="badge bg-success">已通过</span>
                                    {% else %}
                                        <span class="badge bg-danger">已驳回</span>
                                    {% endif %}
                                </td>
                                <td>
                                    {% if record.proof_file %}
                                        <a href="{{ url_for('download_ability_proof', file_id=record.id) }}" class="btn btn-sm btn-secondary">
                                            查看附件
                                        </a>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endif %}
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        {% endif %}
    </div>
</div>

{{  super()  }}
<script>
let bonusCount = 1;
const itemCounts = {
    'academic': 1,
    'social': 1,
    'skill': 1
};

function handleOtherSelect(select) {
    const parentRow = select.closest('.row');
    const otherInput = parentRow.querySelector('.other-input');
    
    if (select.value === 'other') {
        otherInput.style.display = 'block';
        otherInput.required = true;
    } else {
        otherInput.style.display = 'none';
        otherInput.required = false;
    }
}

function addItem(type) {
    if (itemCounts[type] >= 5) {
        alert('最多只能添加5个项目');
        return;
    }
    
    const container = document.getElementById(`${type}-items`);
    const template = `
        <div class="row mb-2">
            <div class="col-md-6">
                <select class="form-select" name="${type}_items[]" onchange="handleOtherSelect(this)">
                    <option value="">请选择项目</option>
                    ${getOptions(type)}
                </select>
                <input type="text" class="form-control mt-2 other-input" name="${type}_other[]" style="display: none;" placeholder="请输入其他项目内容">
            </div>
            <div class="col-md-4">
                <input type="number" class="form-control" name="${type}_scores[]" step="0.1" min="0" max="100" placeholder="分数" required>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn btn-secondary btn-sm" onclick="addItem('${type}')">+</button>
                <button type="button" class="btn btn-danger btn-sm" onclick="removeItem(this)">删除</button>
            </div>
        </div>
    `;
    
    container.insertAdjacentHTML('beforeend', template);
    itemCounts[type]++;
}

function removeItem(button) {
    const row = button.closest('.row');
    const type = row.closest('[id$="-items"]').id.split('-')[0];
    row.remove();
    itemCounts[type]--;
}

function getOptions(type) {
    const options = {
        'academic': [
            ['1', '发表学术论文'],
            ['2', '参与科研项目'],
            ['3', '获得专利'],
            ['4', '参加学科竞赛'],
            ['5', '学术讲座'],
            ['other', '其他']
        ],
        'social': [
            ['1', '社会调研'],
            ['2', '志愿服务'],
            ['3', '实习实践'],
            ['4', '创新创业'],
            ['5', '社会公益'],
            ['other', '其他']
        ],
        'skill': [
            ['1', '外语能力'],
            ['2', '计算机技能'],
            ['3', '职业资格证书'],
            ['4', '艺术特长'],
            ['5', '体育特长'],
            ['other', '其他']
        ]
    };
    
    return options[type].map(([value, text]) => 
        `<option value="${value}">${text}</option>`
    ).join('');
}

// 为所有的select添加change事件监听
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('select[name$="items[]"]').forEach(select => {
        select.addEventListener('change', function() {
            handleOtherSelect(this);
        });
    });
});

function approveScore(type, recordId) {
    if (confirm('确定要通过这条成绩记录吗？')) {
        const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
        console.log('Approving record:', recordId); // 调试信息
        
        fetch(`/approve_${type}/${recordId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': token
            },
            credentials: 'same-origin'
        })
        .then(response => {
            console.log('Response status:', response.status); // 调试信息
            return response.json();
        })
        .then(data => {
            console.log('Response data:', data); // 调试信息
            if (data.success) {
                alert('审核通过成功！');
                window.location.reload();
            } else {
                alert('操作失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请重试');
        });
    }
}

function rejectScore(type, recordId) {
    if (confirm('确定要驳回这条成绩记录吗？')) {
        const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
        console.log('Rejecting record:', recordId); // 调试信息
        
        fetch(`/reject_${type}/${recordId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': token
            },
            credentials: 'same-origin'
        })
        .then(response => {
            console.log('Response status:', response.status); // 调试信息
            return response.json();
        })
        .then(data => {
            console.log('Response data:', data); // 调试信息
            if (data.success) {
                alert('驳回成功！');
                window.location.reload();
            } else {
                alert('操作失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请重试');
        });
    }
}
</script>
{% endblock %} 